package org.mozhu.mboot.backend.system.account.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import lombok.Data;
import org.mozhu.mboot.backend.security.IdentifiedUserDetails;
import org.mozhu.mboot.common.data.entity.IEntity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Entity
@Table(name = "sys_user")
@Data
public class User implements IEntity<Long>{

    private static final long serialVersionUID = 239230219104716120L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // -- 必填项 -- //
    // 姓名
    private String name;

    // 登录名
    private String loginName;

    // 不持久化到数据库，也不显示在Restful接口的属性.
    @Transient
    private String plainPassword;

    // 登录密码
    @JsonIgnore
    private String password;

    private String roles;

    private Boolean activated;

    public IdentifiedUserDetails userDetails() {

        return IdentifiedUserDetails.builder()
                .id(this.getId())
                .username(this.getLoginName())
                .password(this.getPassword())
                .enabled(this.getActivated())
                .authorities(AuthorityUtils.commaSeparatedStringToAuthorityList(this.roles))
                .accountNonLocked(this.getActivated())
                .details(buildDetails())
                .build();
    }

    private Map<String, Serializable> buildDetails() {
        Map<String, Serializable> details = Maps.newHashMap();
        details.put("avatar", "https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png");
        return details;
    }

}
